/*
 * Copyright 2011 Clean GWT
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except
 * in compliance with the License. You may obtain a copy of the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software distributed under the License
 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
 * or implied. See the License for the specific language governing permissions and limitations under
 * the License.
 */
package com.cleangwt.bootstrap.client.ui;

import com.cleangwt.uibinder.client.TemplateSupport;
import com.cleangwt.user.client.AnchorActionEvent;
import com.cleangwt.user.client.AnchorActionEvent.AnchorActionHandler;
import com.cleangwt.user.client.AnchorActionEvent.HasAnchorActionHandlers;
import com.google.gwt.dom.client.Element;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.shared.HandlerRegistration;
import com.google.gwt.user.client.ui.Widget;

/**
 * A droupdown with toggle element and dropdown menu.
 * 
 * @author Jess
 * @version 1.0
 * @since 1.0
 * @see http://getbootstrap.com/javascript/#dropdowns
 */
public class Dropdown extends Widget implements HasAnchorActionHandlers {

  /**
   * Creates a dropdown that wraps an existing &lt;div&gt; element of template.
   * 
   * @param template the template
   * @param element the element to be wrapped
   */
  public static Dropdown wrap(TemplateSupport template, Element e) {
    Dropdown widget = new Dropdown(e);
    template.wrap(widget);
    return widget;
  }

  private boolean selectionHandlerInitialized;

  /**
   * This constructor may be used by subclasses to explicitly use an existing element.
   * 
   * @param element the element to be used
   */
  protected Dropdown(Element element) {
    setElement(element);
  }

  /**
   * Creates a dropdown.
   */
  public Dropdown(String toggleText) {
    this.setElement(DropdownBuilder.createButtonDropdown(toggleText));
  }

  @Override
  public HandlerRegistration addAnchorActionHandler(AnchorActionHandler handler) {
    if (!this.selectionHandlerInitialized) {
      selectionHandlerInitialized = true;
      this.addDomHandler(new ClickHandler() {

        @Override
        public void onClick(ClickEvent event) {
          AnchorActionEvent.translate(Dropdown.this, event);
        }
      }, ClickEvent.getType());
    }
    return addHandler(handler, AnchorActionEvent.getType());
  }

  /**
   * Ensures this dropdown has complete toggle and meun elements, just rebuild it.
   * 
   * @return the dropdown builder.
   */
  public DropdownBuilder build() {
    return new DropdownBuilder(getElement());
  }

}
